# 打开网页
import time
import traceback
from pathlib import Path

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

from pass_by_selenium.tools import *


# 指定 chromedriver 路径


def  init_browser(driver_path):

    # 设置 Chrome 参数
    options = Options()

    options.add_argument("--disable-blink-features=AutomationControlled")  # 防检测

    options.add_argument('--disable-extensions')

    options.add_argument('--no-sandbox')

    options.add_argument('--disable-dev-shm-usage')

    options.add_argument('--disable-gpu')


    # # 禁止图片和css加载
    # prefs = {"profile.managed_default_content_settings.images": 2, 'permissions.default.stylesheet': 2}
    # options.add_experimental_option("prefs", prefs)
    # options.add_argument('--disable-images')  # 可配合 Chrome 插件或 DevTools 限制加载图片

    options.add_experimental_option("excludeSwitches", ["enable-logging"])  # 关闭警告

    options.add_experimental_option("excludeSwitches", ["enable-automation"])  # 防止出现“Chrome正在受到自动测试软件的控制”

    options.add_experimental_option("useAutomationExtension", False)  # 禁用扩展

    # 可选：无头模式（不显示浏览器）
    # 使用无头模式  过去验证码后得到的Cookie不能使用
    # options.add_argument("--headless")

    # 启动 driver
    service = Service(driver_path)
    driver = webdriver.Chrome(service=service, options=options)
    # 执行 JavaScript 删除 navigator.webdriver 特征值
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
                Object.defineProperty(navigator, 'webdriver', {
                    get: () => undefined
                });
            """
    })

    return driver
def set_cookie(driver, cookies):
    for cookie in cookies:
        selenium_cookie = {
            'name': cookie.name,
            'value': cookie.value,
            'domain': cookie.domain,  # 如果报错，可删掉这个字段试试
            'path': cookie.path,
        }
        try:
            driver.add_cookie(selenium_cookie)
        except Exception as e:
            print(f"添加 cookie 出错: {e}, cookie={selenium_cookie}")

def bypass_selenium(cookies,driver):

    # 示例访问
    # 应该清除掉原先的所有Cookie再访问
    # driver.get("file:///D:/html/2.html")


    driver.delete_all_cookies()
    driver.get("https://www.smzdm.com/jingxuan/")
    time.sleep(1)

    """
    set_cookie(driver, cookies)
    driver.get("https://www.smzdm.com/jingxuan/")
    """
    try:
        driver.switch_to.frame(0)

        """
        JS方式
        """

        # 下载背景图
        p1 = download_slider_bg(driver, "#slideBg", 'img1.png')

        # 下载滑块图
        p2 = download_slider_bg(driver, "#tcOperation > div:nth-child(7)", "img2.png")

        # print(f"滑块应该移动到的位置 x = {x}")
        p2 = crop_and_save(p2, (130, 480), (270, 630), "cropped.png")

        # TODO 获取时间  将图片保存为图片，便于判断滑块是否正确通过
        x = detect_displacement(p2, p1, save_path="marked_gap.png")

        if not x:
            print("未找到缺口位置")
        else:
            # 可模拟点击、拖动等操作
            res = drag_captcha_by_js(driver, x)

        time.sleep(0.5)
        driver.save_screenshot("full_page.png")  # 保存截图到当前目录

        if "崩溃啦" in driver.page_source:
            time.sleep(2)
            driver.refresh()
            time.sleep(2)

    except Exception as e:
        # print("发生异常:", e)
        traceback.print_exc("发生异常")

    finally:
        driver.switch_to.default_content()
        print("滑块模拟结束")
        time.sleep(4)
        print("新的cookie => ",driver.get_cookies())
        return driver.get_cookies()


DRIVER = init_browser(Path.cwd()/DRIVER_PATH)

if __name__ == '__main__':
    pass
    # driver_path = "D:\Program Files\Google\Chrome\Application\chromedriver.exe"
    # driver = init_browser(driver_path)
    # bypass_selenium(cookies,driver)


